<?php

//UserTools.class.php

require_once ('model/User.php');

class UserTools {

	//Log the user in. First checks to see if the
	//email and password match a row in the database.
	//If it is successful, set the session variables
	//and store the user object within.
	public static function login($email, $password, $ruolo = "utente")
	{
		$hashedPassword = self::cryptPassword($email, $password);
		$result = mysql_query("SELECT * FROM utente WHERE email = '$email' AND password = '$hashedPassword' AND ruolo = '$ruolo'");
		//exit("SELECT * FROM utente WHERE email = '$email' AND password = '$hashedPassword'");

		if(mysql_num_rows($result) == 1) {
			SessionTools::set('user', new User(mysql_fetch_assoc($result)));
			return true;
		}
		else {
			return false;
		}
	}

	//Log the user out. Destroy the session variables.
	public static function logout() {
			SessionTools::set('user', null);
			SessionTools::close();
	}

	//Check to see if a email exists.
	//This is called during registration to make sure all emails are unique.
	public static function checkEmailExists($email) {
		
		$result = mysql_query("SELECT id FROM utente WHERE email='$email'") or die(mysql_error());
		
		if(mysql_num_rows($result) == 0)
		{
			return false;
		}else{
			return true;
		}
	}
	
	// Verifica il corretto inserimento dei dati utente
	public static function validateUserSignup($data) {

		/*
		$data['nome'] = !empty($signup['nome']) ? $signup['nome'] : "";
		$data['cognome'] = !empty($signup['cognome']) ? $signup['cognome'] : "";
		$data['email'] = !empty($signup['email']) ? $signup['email'] : "";
		$data['password'] = !empty($signup['password']) ? UserTools::cryptPassword($data['email'], $signup['password']) : '';
		$data['ruolo'] = 'utente';
		*/
		
		$errors = array();
		// ... Altri controlli
		if (empty($data['nome'])) {
			$errors['nome'][] = 'Non hai inserito il nome';
		}
		if (empty($data['cognome'])) {
			$errors['cognome'][] = 'Non hai inserito il cognome';
		}
		if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
			$errors['email'][] = 'Email non valida';
		}
		if (UserTools::checkEmailExists($data['email'])) {
			$errors['email'][] = 'Email già presente';
		}
		if (empty($data['password'])) {
			$errors['password'][] = 'Non hai inserito la password';
		}
		if ($data['password'] != $data['rpassword']) {
			$errors['password'][] = 'Le due password non coincidono';
		}
		return $errors;
	}
	

	//get a user
	//returns a User object. Takes the users id as an input
	public static function findById($id)
	{
		$db = new DB();
		$result = $db->select('utente', "id = $id");
		return new User($result);
	}

	public static function getLoggedUser()
	{
		return SessionTools::get('user');
	}

	public static function userIsLogged()
	{
		return SessionTools::exists('user');
	}
	
	public static function userIsRole($role) 
	{
		return SessionTools::exists('user') && SessionTools::get('user')->ruolo == $role;
	}
	
	// Cripta la password utente usando la sua email come salt
	public static function cryptPassword($email, $password) {
		return md5(crypt($password, '$1$' . ereg_replace("[^A-Za-z0-9]", "", strtok($email, '@')) . '$'));
	}
}

?>